//
//  UserPersonalDetailVC.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/26.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "UserPersonalDetailVC.h"
#import "UserGroup.h"
#import "UserArrowItem.h"
#import "UserCenterCell.h"
#import "UserNameController.h"
#import "UserSexAndHandController.h"
#import "UserAdressVC.h"
#import "UserBirthdayVC.h"
#import "NSDate+FormateString.h"
#import "UserPickerController.h"
#import "UserSeriesViewModel.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "PhotoActionSheetViewController.h"
#import "CommunicationManager.h"
#import "UserCenterViewController.h"
#import "UserLevelController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "NSString+Extension.h"

NSString *const userChangeAdressNotification = @"userChangeAdressNotification";

@interface UserPersonalDetailVC ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *changeColorView;
@property (weak, nonatomic) IBOutlet UIView *customNav;

@property (weak, nonatomic) IBOutlet UILabel *titleLable;

@property (nonatomic, strong)UIButton *headIconButton; // 头像


@property (nonatomic, strong) NSMutableArray *groups;

@property (nonatomic, strong) User *user;
@property (nonatomic, strong) UserInforItem *userInforItem;
@property (assign, nonatomic) BOOL changedHeadIcon;


@property (nonatomic, copy) NSString *name; //姓名
@property (assign, nonatomic) GenderType genderType; //性别
@property (nonatomic, copy) NSString *location; // 地址
@property (nonatomic, copy) NSString *birth; // 生日
@property (nonatomic, copy) NSString *signature; // 签名

@property (nonatomic, copy) NSString *height; // 身高
@property (nonatomic, copy) NSString *weight; // 体重
@property (nonatomic, assign)NSInteger hand; // 惯用手
@property (nonatomic, copy) NSString *ballAge; // 球龄
@property (nonatomic, copy)NSString *tennisLevel; // 网球等级
@property (nonatomic, copy)NSString *startTennnisYear; // 网球球龄
@property (nonatomic, copy)NSString *headIconPath; // 头像路径


@end

@implementation UserPersonalDetailVC {
    UserSeriesViewModel *_seriesViewModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.user = [User getLastUser];
    self.userInforItem = [self.user userInforItem];
    
    self.fd_interactivePopDisabled = YES;
    
    _seriesViewModel = [UserSeriesViewModel shareInstance];
    [self loadData];
    self.view.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAdressNotification:) name:userChangeAdressNotification object:nil];
    [self setUPTabelViewUI];
    
    [self.view bringSubviewToFront:self.customNav];
    
    self.titleLable.text = NSLocalizedString(@"Personal Data", nil);
    
    [self configerUserInfro];
    
    self.headIconButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
}

- (void)configerUserInfro {
    
    self.name = self.userInforItem.name;
    self.genderType = self.userInforItem.genderType;
    self.location = self.userInforItem.location;
    self.signature = self.userInforItem.signature;
    self.birth = self.userInforItem.birth;
    
    self.height = self.userInforItem.height;
    self.weight = self.userInforItem.weight;
    self.hand = self.userInforItem.hand;
    self.ballAge = self.userInforItem.ballAge;
    self.headIconPath = self.userInforItem.headIconPath;
    self.startTennnisYear = self.userInforItem.startTennisYear;
    self.tennisLevel = self.userInforItem.tennisLevel;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 点击事件
- (IBAction)backButtonClick:(id)sender {
    // 弹框
    if ([self checkUserInfoChange] == YES) {
        NSString *tipStr2 = NSLocalizedString(@"Whether to save your changes to personal data", nil);
        
        
        
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:tipStr2 message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Save", nil), nil];
        [alertView customizeAppearance];
        
        __weak typeof(self) weakSelf = self;
        
        alertView.onOkAction = ^{
            [weakSelf savaUserInfo];
        };
        alertView.onCancelAction = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        
        [alertView show];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)saveButtonClick:(id)sender {
    
    [self savaUserInfo];
}

- (void)setUPTabelViewUI {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.sectionHeaderHeight = 20;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.headIconButton sd_setImageWithURL:[NSURL URLWithString:self.userInforItem.headIconPath] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"]];
    
    [self CreatTabelViewHeadView];
}

#pragma mark - <网络请求，将用户信息保存到服务器>
- (void)savaUserInfo{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    UIImage *image = self.headIconButton.currentImage;
    if (_changedHeadIcon && image) {
        [YFUserApi uploadImageWithRequestType:kUserUploadHeadImage withImage:image complete:^(NSError *error, NSString *imageUrl) {
            [hud hideAnimated:YES];
            if (error == nil) {
                [self saveInfomation:imageUrl];
            } else {
                [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Save the information failure", nil) afterDelay:1.5];
                // [hud showTextHUDWithMessage:NSLocalizedString(@"Save the information failure", nil) inView:self.view];
            }
        }];
    } else {
        [hud hideAnimated:YES];
        [self saveInfomation:@""];
    }
}

- (void)saveInfomation:(NSString *)imageUrl {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [YFUserApi requestSvaeUserInfoWithUserName:self.name birthday:self.birth isMale:@(self.genderType).stringValue height:self.height weight:self.weight signature:self.signature SportAge:self.ballAge Address:self.location Hand:@(self.hand).stringValue RaketBrand:self.userInforItem.raketBrand  StartTennisYear:self.startTennnisYear Level:self.tennisLevel complete:^(NSError *error) {
        if (error == nil) {
            [hud hideAnimated:YES];
            [self operatoionUserInfo:imageUrl];
            [[NSNotificationCenter defaultCenter] postNotificationName:kUserinfroChangeNotification object:nil];
            [hud showSuccessHudInView:[UIApplication sharedApplication].keyWindow message:NSLocalizedString(@"Successfully Saved", nil)  afterDelay:1.2];
            if ([CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
                [[CommunicationManager shareInstance] performOperationType:OperationTypeHand object:@(self.hand).stringValue completionBlock:^(BOOL success, id feedbackData) {
                    [BTHandler handleHandData:feedbackData withCompletion:^(BOOL success, NSString *hand) {
                        if (!success) {
                            NSLog(@"设置失败");
                        }
                    }];
                }];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [hud hideAnimated:YES];
            [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Save the information failure", nil) afterDelay:1.5];
        }
    }];
}
#pragma mark - DBOperation
- (void)operatoionUserInfo:(NSString *)headIconUrl{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    
    self.userInforItem.name = self.name;
    self.userInforItem.genderType = self.genderType;
    self.userInforItem.location = self.location;
    self.userInforItem.birth = self.birth;
    self.userInforItem.signature = self.signature;
    if (_changedHeadIcon) {
        self.userInforItem.headIconPath = headIconUrl;
    }
    
    self.userInforItem.height = self.height;
    self.userInforItem.weight = self.weight;
    self.userInforItem.hand = self.hand;
    self.userInforItem.ballAge = self.ballAge;
    self.userInforItem.startTennisYear = self.startTennnisYear;
    self.userInforItem.tennisLevel = self.tennisLevel;
    [realm commitWriteTransaction];
}

#pragma mark - 创建头部视图
- (void)CreatTabelViewHeadView {
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, kAutoHei(248))];
    
    UIButton *iconButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.headIconButton = iconButton;
    CGFloat buttonWH = kAutoHei(100);
    CGFloat buttonX = (kYFScreenWidth - buttonWH) * 0.5;
    CGFloat buttonY = kAutoHei(36) + 64;
    iconButton.frame = CGRectMake(buttonX, buttonY, buttonWH, buttonWH);
    
    iconButton.layer.cornerRadius = buttonWH * 0.5;
    iconButton.layer.borderWidth = 3;
    iconButton.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.2].CGColor;
    iconButton.layer.masksToBounds = YES;
    // 设置渐变色
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 1);
    gradientLayer.frame = headView.bounds;
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHex:0x83f09f].CGColor,(__bridge id)[UIColor colorWithHex:0x25c9ad].CGColor];
    
    [headView.layer insertSublayer:gradientLayer atIndex:0];
    [headView addSubview:iconButton];
    
    [iconButton sd_setImageWithURL:[NSURL URLWithString:self.userInforItem.headIconPath] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"competition_icon_defaulImage"]];
    
    [iconButton addTarget:self action:@selector(setHeadIcon) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = headView;
}
- (void)changeAdressNotification:(NSNotification *)note {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    
    item.subTitle = note.object;
    self.location = note.object;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
- (void)loadData {
    
    __weak typeof(self) weakSelf = self;
    
    //    第一组
    UserGroup *group0 = [[UserGroup alloc] init];
    
    UserArrowItem *item0_0 = [UserArrowItem itemWithTitle: NSLocalizedString(@"Nickname", nil) andSubTitle:self.userInforItem.name];
    
    __weak typeof(item0_0) weakItem0_0 = item0_0;
    
    [item0_0 setBlock:^{
        UserNameController *nameVC = [[UserNameController alloc] init];
        nameVC.title = weakItem0_0.title;
        nameVC.userName = weakItem0_0.subTitle;
        
        [nameVC setUserNameBlock:^(NSString *text) {
            weakItem0_0.subTitle = text;
            weakSelf.name = text;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        [weakSelf.navigationController pushViewController:nameVC animated:YES];
    }];
    
    NSString *sexStr = self.userInforItem.genderType == GenderTypeFemale ? NSLocalizedString(@"Female", nil) : NSLocalizedString(@"Male", nil);
    UserArrowItem *item0_1 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Gender", nil) andSubTitle:sexStr];
    __weak typeof(item0_1) weakItem0_1 = item0_1;
    
    [item0_1 setBlock:^{
        UserSexAndHandController *sexVc = [[UserSexAndHandController alloc] init];
        sexVc.title = weakItem0_1.title;
        sexVc.useSettingText = weakItem0_1.subTitle;
        
        [sexVc setUserSexBlock:^(NSString *useSex) {
            weakItem0_1.subTitle = useSex;
            
            weakSelf.genderType = [useSex isEqualToString:NSLocalizedString(@"Female", nil)] ? GenderTypeFemale : GenderTypeMale;
            
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        sexVc.selectType = UserSelectSex;
        [weakSelf.navigationController pushViewController:sexVc animated:YES];
    }];
    
    NSString *cityStr = NSLocalizedString(@"Country", @"城市");
    UserArrowItem *item0_2 = [UserArrowItem itemWithIcon:nil andTitle:cityStr andSubTitle:self.userInforItem.location andTarget:[UserAdressVC class]];
    
    UserArrowItem *item0_3 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Birthday", nil) andSubTitle:self.userInforItem.birth];
    __weak typeof(item0_3) weakItem0_3 = item0_3;
    
    [item0_3 setBlock:^{
        UserBirthdayVC *birthdayVc = [[UserBirthdayVC alloc] init];
        
        birthdayVc.currentBirthdayDate = weakItem0_3.subTitle;
        
        birthdayVc.title = weakItem0_3.title;
        [birthdayVc setSelectBirthdayBlock:^(NSString *birthday) {
            
            weakItem0_3.subTitle = birthday;
            weakSelf.birth = birthday;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        
        [weakSelf.navigationController pushViewController:birthdayVc animated:YES];
    }];
    
    UserArrowItem *item0_4 = [UserArrowItem itemWithTitle:NSLocalizedString(@"User.Signature", nil) andSubTitle:self.userInforItem.signature];
    __weak typeof(item0_4) weakItem0_4 = item0_4;
    
    [item0_4 setBlock:^{
        UserNameController *signNameVC = [[UserNameController alloc] init];
        signNameVC.title = weakItem0_4.title;
        signNameVC.userSignName = weakItem0_4.subTitle;
        
        [signNameVC setUserSignNameBlock:^(NSString *text) {
            weakItem0_4.subTitle = text;
            weakSelf.signature = text;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        
        [weakSelf.navigationController pushViewController:signNameVC animated:YES];
    }];
    
    
    [group0.items addObjectsFromArray:@[item0_0, item0_1, item0_2,item0_3, item0_4]];
    [self.groups addObject:group0];
    
    //    第二组
    UserGroup *group1 = [[UserGroup alloc] init];
    
    UserArrowItem *item1_0 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Height", nil) andSubTitle:[NSString stringWithFormat:@"%@ cm",self.userInforItem.height]];
    __weak typeof(item1_0) weakItem1_0 = item1_0;
    [item1_0 setBlock:^{
        UserPickerController *heightVC = [[UserPickerController alloc] init];
        heightVC.pickerDataSource = [_seriesViewModel heights];
        heightVC.contentKey = weakItem1_0.title;
        heightVC.contenValue = weakItem1_0.subTitle;
        
        [heightVC setSelectCallback:^(NSString *callBackString) {
            weakItem1_0.subTitle = callBackString;
            if (callBackString.length >= 3) {
                weakSelf.height = [callBackString substringToIndex:3];
            }
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        
        [weakSelf.navigationController pushViewController:heightVC animated:YES];
    }];
    
    UserArrowItem *item1_1 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Weight", nil) andSubTitle:[NSString stringWithFormat:@"%@ kg", self.userInforItem.weight]];
    
    __weak typeof(item1_1) weakItem1_1 = item1_1;
    [item1_1 setBlock:^{
        UserPickerController *weightVC = [[UserPickerController alloc] init];
        weightVC.pickerDataSource = [_seriesViewModel weights];
        weightVC.contentKey = weakItem1_1.title;
        weightVC.contenValue = weakItem1_1.subTitle;
        
        [weightVC setSelectCallback:^(NSString *callBackString) {
            weakItem1_1.subTitle = callBackString;
            weakSelf.weight = [callBackString stringByReplacingOccurrencesOfString:@"kg" withString:@""];
            weakSelf.weight = [weakSelf.weight stringByReplacingOccurrencesOfString:@" " withString:@""];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        
        [weakSelf.navigationController pushViewController:weightVC animated:YES];
    }];
    // 左右手类型 0:左手，1:右手
    NSString *handStr = self.userInforItem.hand == 0 ?NSLocalizedString(@"Left hander", nil) : NSLocalizedString(@"Right hander", nil);
    UserArrowItem *item1_2 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Dominant Hand", nil) andSubTitle:handStr];
    __weak typeof(item1_2) weakItem1_2 = item1_2;
    
    [item1_2 setBlock:^{
        UserSexAndHandController *handVc = [[UserSexAndHandController alloc] init];
        handVc.title = weakItem1_2.title;
        handVc.selectType = UserSelectHabitHand;
        handVc.useSettingText = weakItem1_2.subTitle;
        
        [handVc setUserSexBlock:^(NSString *useSex) {
            weakItem1_2.subTitle = useSex;
            weakSelf.hand = [useSex isEqualToString:NSLocalizedString(@"Left hander", nil)] ? 0 : 1;
            
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        
        [weakSelf.navigationController pushViewController:handVc animated:YES];
    }];
    
    //计算具体年份
    NSString *yearStr = [[[NSDate date] formateYearAndMonth] substringToIndex:4];
    
    NSString *startYearStr = [self.userInforItem.startTennisYear trimingAllNumber];
    NSString *startYear = nil;
    if (startYearStr.length < 4) {
        startYear = @"";
    }else {
        NSInteger tennisAge = labs(yearStr.integerValue - startYearStr.integerValue);
        if (tennisAge == 0) {
            startYear = NSLocalizedString(@"Beginner", nil);
        }else {
            startYear = [NSString stringWithFormat:@"%zd %@",tennisAge, NSLocalizedString(@"Unit.years", @"年")];
        }
        
    }
    
    
    UserArrowItem *item1_3 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Training Years", nil) andSubTitle:startYear];
    if (kYFScreenWidth < 375 && [NSBundle currentLangeuage] == kLanguageFrennch) {
        item1_3.title = @"Nbre d'années d'expérience\ntenn";
    }
    
    __weak typeof(item1_3) weakItem1_3 = item1_3;
    [item1_3 setBlock:^{
        UserPickerController *ballOldVC = [[UserPickerController alloc] init];
        ballOldVC.pickerDataSource = [_seriesViewModel tennisExperiences];
        ballOldVC.contentKey = weakItem1_3.title;
        
        ballOldVC.contenValue = weakItem1_3.subTitle;
        
        [ballOldVC setSelectCallback:^(NSString *callBackString) {
            weakItem1_3.subTitle = callBackString;
            
            weakSelf.startTennnisYear = [callBackString stringByReplacingOccurrencesOfString:NSLocalizedString(@"Unit.years", @"年") withString:@""];
            
            if ([weakSelf.startTennnisYear isEqualToString:NSLocalizedString(@"Beginner", nil)]) {
                
                weakSelf.startTennnisYear = yearStr;
            }else {
                weakSelf.startTennnisYear = @(yearStr.integerValue - [[weakSelf.startTennnisYear stringByReplacingOccurrencesOfString:@" " withString:@""] integerValue]).stringValue;
            }
            
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        
        [weakSelf.navigationController pushViewController:ballOldVC animated:YES];
    }];
    
    UserArrowItem *item1_4 = [UserArrowItem itemWithTitle:NSLocalizedString(@"Tennis Rating", nil) andSubTitle:self.userInforItem.tennisLevel];
    __weak typeof(item1_4) weakItem1_4 = item1_4;
    
    [item1_4 setBlock:^{
        
        UserLevelController *levelVc = [[UserLevelController alloc] init];
        levelVc.tennisLevels = [_seriesViewModel tennisLevels];
        levelVc.useSettingText = weakItem1_4.subTitle;
        levelVc.title = weakItem1_4.title;
        [levelVc setUserSelectLevelBlock:^(NSString *levelStr) {
            weakItem1_4.subTitle = levelStr;
            weakSelf.tennisLevel = levelStr;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
        }];
        [weakSelf.navigationController pushViewController:levelVc animated:YES];
    }];
    
    [group1.items addObjectsFromArray:@[item1_0, item1_1, item1_2, item1_3,item1_4 ]];
    
    [self.groups addObject:group1];
    
}

#pragma mark - <从手机中选择图片>
- (void)setHeadIcon {
    
    __weak typeof(self) weakSelf = self;
    [PhotoActionSheetViewController showInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        if (btnType == kTapAlbumButton) {
            [weakSelf takePhotoByPhotos];
        } else  if (btnType == kTapCameraButton) {
            [weakSelf takePhotoByCamera];
        }
    }];
}
- (void)takePhotoByCamera{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)takePhotoByPhotos{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Can't get camera or photo information", nil) inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [self.headIconButton setImage:info[UIImagePickerControllerOriginalImage] forState:UIControlStateNormal];
    _changedHeadIcon = YES;
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

#pragma mark - dataSoureDelegate & UitableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.groups.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.groups[section] items].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UserCenterCell *cell = [UserCenterCell settingViewCellTableView:tableView withStyle:UITableViewCellStyleValue1];
    
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    cell.item = item;
    if (indexPath.row == group.items.count - 1) {
        [cell showLine:NO];
    }else {
        [cell showLine:YES];
    }
    if (indexPath.row == 0) {
        [cell showSectionSepTopLineView:YES];
    }else {
        [cell showSectionSepTopLineView:NO];
    }
    
    return cell;
}
// 选中的哪一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    
    if (item.block) {
        item.block();
        return;
    }
    
    if ([item isKindOfClass:[UserArrowItem class]]) {
        
        UserArrowItem *arrowItem = (UserArrowItem *)item;
        if (arrowItem.target) {
            Class class = arrowItem.target;
            UIViewController *vc = [[class alloc] init];
            vc.title = item.title;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kAutoHei(44);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    UserGroup *group = self.groups[section];
    
    if (group.headHeight <= 0) {
        return 20;
    }else {
        return group.headHeight;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UserGroup *group = self.groups[section];
    
    if (group.headerTitle != nil) {
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, group.headHeight)];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, kYFScreenWidth - 20, headView.bounds.size.height)];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor colorWithHex:0xaaaaaa];
        
        label.text = group.headerTitle;
        
        [headView addSubview:label];
        
        headView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
        
        return headView;
    }else {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
        return view;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0.01;
    }else {
        return 64;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat contentOffY = scrollView.contentOffset.y;
    
    if (contentOffY < 0) {
        self.tableView.backgroundColor = [UIColor colorWithHex:0x83f09f];
        self.changeColorView.alpha = 0;
    }else {
        self.tableView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
        if (contentOffY >=0 && contentOffY <= 64) {
            CGFloat scale = contentOffY / 64;
            self.changeColorView.alpha = scale;
        }else {
            self.changeColorView.alpha = 1;
            
        }
    }
}

- (NSMutableArray *)groups {
    if (_groups == nil) {
        _groups = [NSMutableArray array];
    }
    return _groups;
}

- (BOOL)checkUserInfoChange {
    if (![self.name isEqualToString:self.userInforItem.name]) {
        // NSLog(@"name");
        return YES;
    }
    if (self.genderType != self.userInforItem.genderType) {
        // NSLog(@"genderType");
        return YES;
    }
    if (![self.location isEqualToString:self.userInforItem.location]) {
        // NSLog(@"location");
        return YES;
    }
    if (![self.signature isEqualToString:self.userInforItem.signature]) {
        // NSLog(@"signature");
        return YES;
    }
    if (![self.height isEqualToString:self.userInforItem.height]) {
        NSLog(@"height");
        return YES;
    }
    if (![self.weight isEqualToString:self.userInforItem.weight]) {
        // NSLog(@"name");
        return YES;
    }
    if (![self.weight isEqualToString:self.userInforItem.weight]) {
        // NSLog(@"weight");
        return YES;
    }
    if (self.hand != self.userInforItem.hand) {
        //NSLog(@"hand");
        return YES;
    }
    if (![self.startTennnisYear isEqualToString:self.userInforItem.startTennisYear]) {
        //NSLog(@"startTennnisYear");
        return YES;
    }
    if (![self.tennisLevel isEqualToString:self.userInforItem.tennisLevel]) {
        // NSLog(@"tennisLevel");
        return YES;
    }
    return NO;
}

@end

